<template>
  <div class="search-form">
    <!-- 头部tab切换 -->
    <el-row type="flex" class="search-tab">
      <span
        v-for="(item, index) in tabs"
        :key="index"
        @click="handleSearchTab(item, index)"
        :class="{ active: index === currentTab }"
      >
        <i :class="item.icon"></i>
        {{ item.name }}
      </span>
    </el-row>

    <el-form class="search-form-content" ref="form" label-width="80px">
      <el-form-item label="出发城市">
        <!-- fetch-suggestions 返回输入建议的方法 -->
        <!-- select 点击选中建议项时触发 -->
        <el-autocomplete
          :fetch-suggestions="queryDepartSearch"
          placeholder="请搜索出发城市"
          :trigger-on-focus="false"
          :highlight-first-item="true"
          @select="handleDepartSelect"
          class="el-autocomplete"
          v-model="form.departCity"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="到达城市">
        <el-autocomplete
          :fetch-suggestions="queryDestSearch"
          placeholder="请搜索到达城市"
          @select="handleDestSelect"
          :trigger-on-focus="false"
          class="el-autocomplete"
          v-model="form.destCity"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="出发时间">
        <!-- change 用户确认选择日期时触发 -->
        <el-date-picker
          v-model="form.departDate"
          type="date"
          placeholder="请选择日期"
          style="width: 100%"
          @change="handleDate"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label>
        <el-button
          style="width: 100%"
          type="primary"
          icon="el-icon-search"
          @click="handleSubmit"
          >搜索</el-button
        >
      </el-form-item>
      <div class="reverse">
        <span @click="handleReverse">换</span>
      </div>
    </el-form>
  </div>
</template>

<script>
import moment from "moment";
export default {
  data() {
    return {
      tabs: [
        { icon: "iconfont icondancheng", name: "单程" },
        { icon: "iconfont iconshuangxiang", name: "往返" },
      ],
      currentTab: 0,
      form: {
        departCity: "", //出发城市
        departCode: "", //出发城市代码
        destCity: "", //目标城市
        destCode: "", //目标城市代码
        departDate: "", //日期 2019-05-01
      },
    };
  },
  methods: {
    // tab切换时触发
    handleSearchTab(item, index) {
      // this.currentTab = index;
      if (index == 1) {
        this.$confirm("目前暂不支持往返，请使用单程选票！", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning",
        });
      }
    },

    // 出发城市输入框获得焦点时触发
    // value 是选中的值，cb是回调函数，接收要展示的列表
    // 1.根据用户的输入查询输入建议
    // 出发城市输入框获得焦点时触发
    // value 是选中的值，cb是回调函数，接收要展示的列表
    queryDepartSearch(value, cb) {
      // JiPiao - 实时机票城市：http:127.0.0.1:1337/airs/city
      // 目标城市输入框获得焦点时触发
      // value 是选中的值，cb是回调函数，接收要展示的列表
      this.getSuggestions(value, "depart", cb);
    },
    // JiPiao - 实时机票城市：http:127.0.0.1:1337/airs/city
    getSuggestions(value, type, cb) {
      this.$axios({
        url: "/airs/city",
        params: { name: value },
      }).then((res) => {
        console.log(res);
        let list;
        if (res.data.data.length == 0) {
          cb([{ value: "没有查询到相应的城市" }]);
          return;
        }
        // 改造的查询数据匹配组件的需要
        list = res.data.data.map((v) => {
          // 这里为什么要做改造，因为autocomplete组件规定，只有对象中的Value属性才会显示
          return {
            value: v.name,
            code: v.sort,
          };
        });
        // 过滤掉没有Code的城市，因为它不可能会购票成功
        list = list.filter((v) => {
          return v.code; // 不为null则需要
        });
        console.log(list);
        if (type == "depart") {
          this.form.departCity = list[0].value;
          this.form.departCode = list[0].code;
        } else {
          this.form.destCity = list[0].value;
          this.form.destCode = list[0].code;
        }
        cb(list);
      });
    },

    // 目标城市输入框获得焦点时触发
    // value 是选中的值，cb是回调函数，接收要展示的列表
    queryDestSearch(value, cb) {
      this.getSuggestions(value, "dest", cb);
    },

    // 出发城市下拉选择时触发
    handleDepartSelect(item) {
      console.log(item);
      this.form.departCity = item.value;
      this.form.departCode = item.code;
    },

    // 目标城市下拉选择时触发
    handleDestSelect(item) {
      this.form.destCity = item.value;
      this.form.destCode = item.code;
    },

    // 确认选择日期时触发
    handleDate(value) {
      this.form.departDate = moment(value).format("YYYY-MM-DD");
    },

    // 触发和目标城市切换时触发
    handleReverse() {
      let { departCity, departCode, destCity, destCode } = this.form;
      this.form.departCity = destCity;
      this.form.departCode = destCode;

      this.form.destCity = departCity;
      this.form.destCode = departCode;
    },

    // 提交表单是触发
    handleSubmit() {
      // 添加用户输入验证，如果验证不通过，则不进行页面的跳转
      // 1.添加验证规则
      let rules = {
        depart: {
          value: this.form.departCity,
          message: "请选择出发城市",
        },
        dest: {
          value: this.form.destCity,
          message: "请选择到达城市",
        },
        date: {
          value: this.form.departDate,
          message: "请选择出发时间",
        },
      };
      // 2.设置验证是否通过的标记，默认为true,后期只有一个验证不通过就为false
      let flag = true;
      // 3.遍历验证规则  Object.keys(rules) >> ['depart','dest','date']
      Object.keys(rules).forEach((v) => {
        let item = rules[v];
        // 判断是否输入的内容
        if (!item.value) {
          // 当前数据没有内容
          flag = false;
          this.$confirm(item.message, "提示", {
            confirmButtonText: "确定",
            showCancelButton: false,
            type: "warning",
          });
          return;
        }
      });

      if (!flag) {
        return;
      }
      // 清除城市名称中的  市  字
      this.form.departCity =
        this.form.departCity.indexOf("市") != -1
          ? this.form.departCity.replace("市", "")
          : this.form.departCity;
      this.form.destCity =
        this.form.destCity.indexOf("市") != -1
          ? this.form.destCity.replace("市", "")
          : this.form.destCity;
      console.log(this.form);
      // 将当前的搜索记录存储到store
      this.$store.commit("history/saveFlightHistory", this.form);
      // 跳转路由，同时传递参数
      this.$router.push({ path: "/air/flights", query: this.form });
    },
  },
  mounted() {},
};
</script>

<style scoped lang="less">
.search-form {
  border: 1px #ddd solid;
  border-top: none;
  width: 360px;
  height: 350px;
  box-sizing: border-box;
}

.search-tab {
  span {
    display: block;
    flex: 1;
    text-align: center;
    height: 48px;
    line-height: 42px;
    box-sizing: border-box;
    border-top: 3px #eee solid;
    background: #eee;
  }

  .active {
    border-top-color: orange;
    background: #fff;
  }

  i {
    margin-right: 5px;
    font-size: 18px;

    &:first-child {
      font-size: 16px;
    }
  }
}

.search-form-content {
  padding: 15px 50px 15px 15px;
  position: relative;

  .el-autocomplete {
    width: 100%;
  }
}

.reverse {
  position: absolute;
  top: 35px;
  right: 15px;

  &:after,
  &:before {
    display: block;
    content: "";
    position: absolute;
    left: -35px;
    width: 25px;
    height: 1px;
    background: #ccc;
  }

  &:after {
    top: 0;
  }

  &:before {
    top: 60px;
  }

  span {
    display: block;
    position: absolute;
    top: 20px;
    right: 0;
    font-size: 12px;
    background: #999;
    color: #fff;
    width: 20px;
    height: 20px;
    line-height: 18px;
    text-align: center;
    border-radius: 2px;
    cursor: pointer;

    &:after,
    &:before {
      display: block;
      content: "";
      position: absolute;
      left: 10px;
      width: 1px;
      height: 20px;
      background: #ccc;
    }

    &:after {
      top: -20px;
    }

    &:before {
      top: 20px;
    }
  }
}
</style>
